package com.jf.controller;

import com.alibaba.fastjson.JSON;
import com.jf.bean.Role;
import com.jf.bean.Userinfo;
import com.jf.service.RoleService;
import com.jf.service.impl.RoleServiceImpl;
import com.jf.util.MyUtils;
import com.jf.util.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@WebServlet("/role")
public class RoleServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        RoleService roleService = new RoleServiceImpl();

        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        String result = MyUtils.getRequestJson(in);
        Role role = JSON.parseObject(result,Role.class);

        if("select".equals(param)){
            response.getWriter().println(JSON.toJSON(roleService.getSelect()));
        }

        if(MyUtils.isStringEmpty(param)){
            request.getRequestDispatcher("/WEB-INF/pages/admin/role/role-list.jsp").forward(request,response);
        }
        if("edit".equals(param)){
            request.getRequestDispatcher("/WEB-INF/pages/admin/role/role-edit.jsp").forward(request,response);
        }
        if("list".equals(param)){
            int page = MyUtils.string2Int(request.getParameter("page"),1);
            int limit = MyUtils.string2Int(request.getParameter("limit"),5);
            PageInfo pageInfo = new PageInfo(page,limit);
            /*分页筛选需要的role是通过get请求传递的参数，需要单独处理*/
            Role searchInfo = new Role();
            searchInfo.setRoleName(request.getParameter("roleName"));
            response.getWriter().println(JSON.toJSON(roleService.getPage(pageInfo,searchInfo)));
        }
        if("info".equals(param)){
            int id = MyUtils.string2Int(request.getParameter("id"));
            response.getWriter().println(JSON.toJSON(roleService.info(id)));
        }
        if("update".equals(param)){
            response.getWriter().println(JSON.toJSON(roleService.saveOrUpdate(role)));
        }
        if("delete".equals(param)){
            int[] ids = MyUtils.string2IntArray(request.getParameter("ids"));
            if(ids == null){
                ids=new int[]{role.getId()};
            }
            response.getWriter().println(JSON.toJSON(roleService.delete(ids)));
        }
    }
}
